from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from decimal import Decimal

from meiduo_mall.utils.views import LoginRequiredMixin
from goods.models import SKU
from users.models import Address


# Create your views here.


class OrderSettlementView(LoginRequiredMixin, View):
    """计算订单"""

    def get(self, request):
        """提供订单结算页面"""

        user = request.user
        # 查询用户收货地址:查询登录用户没有被删除的收货地址
        try:
            addresses = Address.objects.filter(user=user, is_deleted=False)
        except Address.DoesNotExist:
            # 如果地址为空，渲染模板时会判断，并跳转到地址编辑页面
            addresses = None

        # 查询购物车中被勾选的商品
        redis_conn = get_redis_connection('carts')
        # 购物车所有数据，包含勾选和未勾选
        redis_carts = redis_conn.hgetall('carts_%s' % user.id)
        # 被勾选的商品sku_id
        redis_selected = redis_conn.smembers('selected_%s' % user.id)

        # 构造购物车中被勾选的商品列表数据
        new_cart_dict = {}
        for sku_id in redis_selected:
            new_cart_dict[int(sku_id)] = int(redis_carts[sku_id])

        # 查询商品信息
        # 遍历new_cart_dict 取出sku_id和count
        skus = SKU.objects.filter(id__in=new_cart_dict.keys())
        total_count = 0
        total_amount = Decimal(0.00)
        for sku in skus:
            sku.count = new_cart_dict[sku.id]
            sku.amount = sku.count * sku.price
            # 计算总数量和总金额
            total_count += sku.count
            total_amount += sku.amount

        # 补充运费
        freight = Decimal('10.00')

        context = {
            'addresses': addresses,
            'skus': skus,
            'total_count': total_count,
            'total_amount': total_amount,
            'freight': freight,
            'payment_amount': total_amount + freight
        }
        return render(request, 'place_order.html', context)
